<?php
/**
 * Created by Benjiemin
 * Date: 2020/3/4
 * Time: 16:23
 */

require ('./vendor/autoload.php');
use QL\QueryList;

require ('./aip-php-sdk-2.2.15/AipOcr.php');
 $baseUrl = 'http://nc1.win3008.com/';
 $username = 'nn301';
 $password = 'qwe123123';
    $header = [
        'timeout' => 30,
        'headers' => [
            'Referer' => $baseUrl,
            'Pragma' => 'no-cache',
            'Cache-Control' => 'no-cache',
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
            'Accept' => '*/*',
            'Accept-Encoding' => 'gzip, deflate',
            'Upgrade-Insecure-Requests' => '1',
            'Origin' => $baseUrl,
            'Connection' => 'keep-alive'
        ]
    ];

/**
 * @param $gameTypeLann
 * @param $location位置
 * @param $betBall投注球
 */
 function switchCode($gameTypeLann, $location, $betBall)
{
    switch ($gameTypeLann) {
        case '8'://幸运飞艇
            if (strlen($location) > 1) {
                $location = substr($location, 1, 1);
            }
            return $gameTypeLann . str_pad(($betBall - 1), 2, 0, STR_PAD_LEFT) . $location;
            break;
        default:
            return 0;
    }
}

/**
 * 获取赔率请求地址
 */
 function getRateUrl($code, $times = 0)
{
    if ($times > 2) {
        return false;
    }
    $selfCode = switchLotteryCode($code);
    if (!$selfCode) {
        return false;
    }

    switch ($selfCode) {
        case '8'://幸运飞艇
            $url = "member/pt8/betdrawxmldata/?pcid2=801,802,803,804,805,806,807,808,809,810&0.".time();
            break;
        case '3'://重庆欢乐生肖
            $url =  "member/pt3/betdrawxmldata/?pcid2=301,302,303,304,305,306,307,308,309,310,311,312,313&0.3551725915163002";
            break;
        case '2'://广东快乐10分
            $url =  "member/pt2/betdrawxmldata/?pcid2=209,210,211,212,215,216,217,218&0.5876573288814646";
            break;
        case '4'://北京赛车PK10
            $url =  "member/pt4/betdrawxmldata/?pcid2=411,412,413,414,415&0.21742188705714427";
            break;
        case '7'://PC蛋蛋
            $url =  "member/pt7/betdrawxmldata/?pcid2=702,703,704,705,706,707,711,712,713,714&0.08398506963838814";
            break;
        case '9'://新疆时时彩
            $url =  "member/pt9/betdrawxmldata/?pcid2=901,902,903,904,905,906,907,908,909,910,911,912,913&0.4341335102617949";
            break;
        case '10'://澳洲欢乐5
            $url =  "member/pt10/betdrawxmldata/?pcid2=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013&" . time();
            break;
        default:
            $url =  'member/pt9/betdrawxmldata/';
    }
    return $url;
}

/**把彩票代码转换为win3008彩票代码
 * @param $code
 * @return bool|mixed
 */
 function switchLotteryCode($code)
{
    $codeArr = array(
        '10005' => 2,//广东快乐10分
        '50021' => 3,//重庆欢乐生肖
        '10001' => 4,//北京赛车PK10
        '4' => 7,//Pc蛋蛋
        '10136' => 8,//幸运飞艇
        '10004' => 9,//新疆时时彩
        '7' => 10,//澳洲欢乐5
        '8' => 11,//澳洲欢乐10
        '9' => 12,//极速时时彩
        '10' => 13,//极速赛车
    );
    if (isset($codeArr[$code])) {
        return $codeArr[$code];
    }
    return false;
}

/**下单回调
 * @param $orderno
 * @param $ret
 */
 function callBack($orderno,$ret){
    $callBackUrl = 'http://106.52.105.157:81/order/bet-status-callback';
    echo "回传下单结果，订单号{$orderno}，结果：{$ret}".PHP_EOL;
    QueryList::post($callBackUrl, [
        'orderno' => $orderno,
        'ret' => $ret,//成功1，不成功0
    ],
        [
            'timeout' => 30,
            'headers' => [
                'Referer' => 'http://nc1.win3008.com/lottery/pt8/css/ball.css',
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
                'Accept'     => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'Accept-Encoding'      => 'gzip, deflate',
                'Upgrade-Insecure-Requests'=>'1',
                'Origin'=>'http://nc1.win3008.com/',
                'Host'=>'nc1.win3008.com',
            ]
        ]
    );
}


//进入网页
$jar = new \GuzzleHttp\Cookie\CookieJar;
$client = new GuzzleHttp\Client(['cookies' => true]);

$ql = $client->request('GET', $baseUrl, [
    'cookies' => $jar
]);
if($ql->getStatusCode()!=200){
    echo '网站状态不正常';die;
}

$imgUrl = $baseUrl.'public/captcha.php';
//下载验证码到本地
$ql = $client->request('GET', $imgUrl);
$imgname = 'code.jpeg';
file_put_contents($imgname,$ql->getBody(), true);

//验证码识别
$appId = '9360309';
$apiKey = 'f94FyaKX2LKx0GWBoddFVpxa';
$secretKey = 'oGhM9QqHH6qslErF1LH8etP6Ber5adDz';
$apiOcrModel = new AipOcr($appId, $apiKey, $secretKey);
$verifyRet = $apiOcrModel->basicGeneral(file_get_contents($imgname));
if(!isset($verifyRet['words_result'][0]['words'])){
    echo '识别失败'.PHP_EOL;die;
}

$ValidateCode = $verifyRet['words_result'][0]['words'];
//登录
$ql = $client->request('POST',$baseUrl.'member/login/check/',[
    'form_params'=>[
        'loginName' => $username,
        'loginPwd' => $password,
        'ValidateCode'=>$ValidateCode,
        'Submit'=>'',
]
]);

//登录确认
$ql = $client->request('POST',$baseUrl.'member/main',[
    'form_params'=>[
        'prRead' => '',
        'Sagree'=>'yes',
    ]
]);

//跳转新闻界面
$ql = $client->request('GET',$baseUrl.'news/text/0?0.21222746993288832');

   //拉订单
    $time = time();
    $i = 1;
    while((time()-$time)<6000){
        //拉取订单
        $url = 'http://106.52.105.157:81/';
        $orderJson = QueryList::get($url.'order/get-member-order')->getHtml();
        echo "第{$i}次拉取订单".PHP_EOL;
        $i = $i+1;
        if(empty( $orderJson)){
            echo '订单获取失败'.PHP_EOL;
            sleep(1);
            continue;
        }

        $dataArr = json_decode($orderJson,true);
        $orderDataArr = $dataArr['data'];
        if(empty($orderDataArr)){
            echo '没有订单数据'.PHP_EOL;
            sleep(1);
            continue;
        }
        echo '收到订单，开始遍历订单'.PHP_EOL;
        foreach ($orderDataArr as $order){
            $betBallsArr = explode(',' ,$order['bet_balls']);
            sleep(5);
            //获取赔率
            $rateUrl = $baseUrl.getRateUrl($order['gameid']);
            $ql = $client->request('GET',$rateUrl);
            $html = $ql->getBody();
            file_put_contents('peilv.html',$html);
            $ql = QueryList::html($html);
            // 获取投注期号
            $drawid = $ql->find('root periodid')->text();
            if(empty($drawid)){
                echo 'drawid获取失败或者未开盘'.PHP_EOL;
                callBack($order['orderno'],0);
                sleep(1);continue;
            }

            //余额,这边需求投注之前判断余额
            $balance = $ql->find('root balance')->text();
            if(empty($balance)){
                echo 'balance获取失败'.PHP_EOL;
                callBack($order['orderno'],0);
                sleep(1);continue;
            }

            $gameTypeLann = switchLotteryCode($order['gameid']);
            $pidStr = '';
            $oddStr = '';
            $betMoneyStr = '';
            var_dump($order);
            //生成订单数据
            foreach ($betBallsArr as $betBall){
                $betMoneyStr = $betMoneyStr.','.$order['bet_money'];
                $p_id = switchCode($gameTypeLann,$order['bet_number'],$betBall);
                $p_id_odd = $ql->find("bet[id={$p_id}]")->text();
                $drawperiod = $ql->find("drawperiod")->text();
                $drawperiod = str_replace('-','',$drawperiod);
                if($drawperiod!=$order['issue']){
                    echo "期号不一致，drawperiod={$drawperiod},issue={$order['issue']}".PHP_EOL;continue;
                }
                if(!empty($p_id)){
                    $pidStr = $pidStr.','.$p_id;
                }
                if(empty($p_id_odd)){
                    sleep(3);
                    $ql = QueryList::html($html);
                    $p_id_odd = $ql->find("bet[id={$p_id}]")->text();
                }
                $oddStr = $oddStr.','.$p_id_odd;
            }
            $pidStr = trim($pidStr,',');
            $oddStr = trim($oddStr,',');
            $betMoneyStr = trim($betMoneyStr,',');
            $betUrl = $baseUrl.'member/bet/'.$gameTypeLann;

            //投注
            $ql = $client->request('POST',$betUrl,[
                'form_params'=>[
                    'draw_ID' => ($drawid),
                    'p_ID'=>$pidStr,
                    'p_Odds' => $oddStr,
                    'bet_Money' =>$betMoneyStr,
                    'checksum' => mt_rand(10000,99999),
                    'ms_1' => '50',
                    'ms_2' => '100',
                    'ms_3' => '200',
                    'ms_4' => '500',
                    'ms_5' => '1000',
                    'ms_6' => '5000',
                ]
            ]);

            echo "第{$i}次投注订单".PHP_EOL;
            //投注结束，判断投注结果
            file_put_contents($order['orderno'].'ret.html', $ql->getBody());
            $ret = 1;
            if(strpos($html,'盘口未开盘')!==false){
                $ret = 0;
            }
            //判断下单是否成功，并回调
            callBack($order['orderno'],$ret);

        }
    }


